package com.lancoo.androidmultichatroom.demo;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lancoo.tyjx.multichatroom.activity.MyApplication;
import com.lancoo.tyjx.multichatroom.constants.Constants;
import com.lancoo.tyjx.multichatroom.expression.ExpressionView;
import com.lancoo.tyjx.multichatroom.model.ChatItem;
import com.lancoo.tyjx.multichatroom.model.Room;
import com.lancoo.tyjx.multichatroom.model.User;
import com.lancoo.tyjx.multichatroom.utils.MyAndroidUtil;
import com.lancoo.tyjx.multichatroom.utils.Tool;
import com.lancoo.tyjx.multichatroom.view.RecordButton;
import com.lancoo.tyjx.multichatroom.xmpp.XmppLoadThread;
import com.lancoo.tyjx.multichatroom.xmpp.XmppTool;
import org.jivesoftware.smack.SmackAndroid;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Presence;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    @BindView(R.id.expBtn)
    ImageView mExpBtn;
    @BindView(R.id.msgText)
    EditText mMsgText;
    @BindView(R.id.recordBtn)
    RecordButton mRecordBtn;
    @BindView(R.id.edicting_layout)
    RelativeLayout mEdictingLayout;
    @BindView(R.id.expView)
    ExpressionView mExpView;
    @BindView(R.id.ll_chat_bottom)
    LinearLayout mLlChatBottom;
    @BindView(R.id.tv_send)
    TextView mTvSend;
    @BindView(R.id.sendBtn)
    ImageView mSendBtn;
    @BindView(R.id.iv_image)
    ImageView mIvImage;

    private SmackAndroid mSmack;
    private String mUser_name;
    private String pwd;
    private XmppLoadThread createThread;
    private XmppLoadThread joinThread;
    private List<Room> rooms;

    private final static int JOIN_GROUP_CHAT = 2;
    private final static int LOGIN_ACCOUNT = 4;

    private boolean mjoinroomstate = false;

    private Handler mhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case JOIN_GROUP_CHAT:
                    joinMultiRoom(Constants.USER_NAME, ConstDefine.RoomName);
                    break;
                case LOGIN_ACCOUNT:
                    buildConnected(ConstDefine.UserID.toLowerCase(), pwd);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        mSmack = SmackAndroid.init(this);
        mUser_name = MyApplication.sharedPreferences.getString(Constants.LOGIN_ACCOUNT, null);
        pwd = "123456";

        setXmpp();

        joinChatRoom();
    }

    private void setXmpp() {
        Constants.SERVER_HOST = "60.190.136.238";
        Constants.SERVER_PORT = 15223;
    }

    private void joinChatRoom() {
        Log.i(TAG, "jionChatRoom: ");
        String userId = ConstDefine.UserID;
        //如果用户名未空，或者当前用户名不等于之前保存的用户名
        if (!TextUtils.isEmpty(userId)) {
            if (mUser_name == null || !(mUser_name.equals(userId.toLowerCase()))) {
                createAccount(userId.toLowerCase(), "123456"); //zzw0022
            } else {
                buildConnected(userId.toLowerCase(), pwd);//
                Log.i(TAG, "jionChatRoom: mUser_name " + mUser_name + " pwd " + pwd);
            }
        }
    }

    private void createAccount(final String userName, final String passWord) {
        Log.i(TAG, "createAccount: userName " + userName);
        createThread = new XmppLoadThread(this) {

            @Override
            protected Object load() {
                IQ result = null;
                try {
                    result = XmppTool.getInstance().regist(userName, passWord);
                    if (result != null && result.getType() == IQ.Type.RESULT) {
                        XmppTool.getInstance().closeConnection();
                        //完善信息
                        Constants.loginUser = new User();
                        Constants.loginUser.username = userName;

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return result;
            }

            @Override
            protected void result(Object object) {
                IQ result = (IQ) object;
                if (result == null) {
                    Tool.initToast(getApplicationContext(), getString(R.string.service_result));
                } else if (result.getType() == IQ.Type.ERROR) {
                    if (result.getError().toString().equalsIgnoreCase("conflict(409)")) {
                        Log.i(TAG, "result: 账号已经存在");
                        XmppTool.getInstance().closeConnection();
                        mhandler.sendEmptyMessage(LOGIN_ACCOUNT);
                    } else {
                        Tool.initToast(getApplicationContext(), getString(R.string.register_fail));
                    }
                } else if (result.getType() == IQ.Type.RESULT) {
                    MyAndroidUtil.editXmlByString(Constants.LOGIN_ACCOUNT, userName);
                    MyAndroidUtil.editXmlByString(Constants.LOGIN_PWD, passWord);
                    MyAndroidUtil.editXml(Constants.LOGIN_CHECK, true);

                    mUser_name = userName;
                    pwd = passWord;
                    mhandler.sendEmptyMessage(LOGIN_ACCOUNT);
                }
            }

        };

    }

    public void joinMultiRoom(final String user, final String roomID) {
        Log.i(TAG, "joinMultiRoom: user " + user);

        joinThread = new XmppLoadThread(getApplication()) {

            @Override
            protected Object load() {
                boolean issuccess = false;
                issuccess = XmppTool.getInstance().joinMultiUserChat(user,
                        roomID, false);
                mjoinroomstate = issuccess;
                return issuccess;
            }

            @Override
            protected void result(Object object) {
                boolean result = (boolean) object;
                XmppTool.getInstance().setRecevier(ConstDefine.RoomName, ChatItem.GROUP_CHAT);
                if (result) {
                    mjoinroomstate = true;
                    ChatFragment fragment = (ChatFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
                    fragment.setMessage(ConstDefine.ScheduleID, ConstDefine.ScheduleID.toLowerCase(), ConstDefine.CourseName + "讨论组", ConstDefine.RoomName, ConstDefine.ScheduleID.toLowerCase(), ChatItem.GROUP_CHAT,
                            mExpBtn, mMsgText, mRecordBtn, mSendBtn, mEdictingLayout, mIvImage, mExpView, mTvSend);
                } else {
                    mjoinroomstate = false;
                    ChatFragment fragment = (ChatFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
                    fragment.showSuccess(false);
                }
            }
        };
    }

    private void buildConnected(final String userName, final String pwd) {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.i(TAG, "buildConnected: userName " + userName + "    pwd " + pwd + "  SERVER_HOST " + Constants.SERVER_HOST);
                    // 连接
//                    Log.i(TAG, "buildConnected: isConnected 11 " + XmppTool.getInstance().isconnected());
                    XMPPConnection conn = null;
                    if (!XmppTool.getInstance().isconnected()) {
//                        XmppTool.getInstance().getConnection().login(userName, pwd);
                        conn = XmppTool.getInstance().getConnection();
                        if (conn != null) {
                            conn.login(userName, pwd);
                            String userInfo = XmppTool.getInstance().getConnection().getUser();
                            Log.i("XMPPClient", "Logged in as =============userInfo=================" + userInfo);
                            if (!"".equalsIgnoreCase(userInfo)) {
                                rooms = XmppTool.getInstance().getMyRooms();
                                Log.i("XMPPClient", "Logged in as =============rooms.size()=================" + rooms.size());
                            }

                        } else {
                            Tool.initToast(getApplicationContext(), "连接服务器失败！");
                            return;
                        }
                    }

                    Log.i(TAG, "buildConnected: isConnected " + XmppTool.getInstance().isconnected());
//                    initHostRoom(conn);

                    // 状态
                    Presence presence = new Presence(Presence.Type.available);
                    XmppTool.getInstance().getConnection().sendPacket(presence);
                    Constants.USER_NAME = ConstDefine.UserType + "&" + ConstDefine.UserID.toLowerCase() + "&" + ConstDefine.UserName;
                    Constants.PWD = pwd;
                    MyAndroidUtil.editXmlByString(Constants.LOGIN_ACCOUNT, userName);
                    MyAndroidUtil.editXmlByString(Constants.LOGIN_PWD, pwd);
                    Log.i(TAG, "buildConnected run: login success");

                    mhandler.sendEmptyMessage(JOIN_GROUP_CHAT);
                } catch (XMPPException e) {
                    Tool.initToast(getApplicationContext(), "连接服务器失败！");
                    XmppTool.getInstance().closeConnection();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}
